package cn.kgc.conmanager.controller;

import cn.kgc.conmanager.entity.ResultEntity;
import cn.kgc.conmanager.pojo.Contact;
import cn.kgc.conmanager.service.ContactService;
import com.github.pagehelper.PageInfo;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;

/**
 * @author shkstart
 * @create 郭祥伟
 */
@RestController
public class ContactController {
    @Resource
    ContactService contactService;
    @RequestMapping("/select/contact")
    public ResultEntity<PageInfo<Contact>> selectContact(
            @RequestParam(value = "cname",required = false,defaultValue = "") String  cname,
            @RequestParam(value = "pageNum",required = false,defaultValue = "1") Integer pageNum,
            @RequestParam(value = "pageSize",required = false,defaultValue = "4") Integer pageSize
    ){
        PageInfo<Contact> pageInfo=contactService.select(pageNum,pageSize, cname);
        return ResultEntity.successWithoutData(pageInfo);
    }
    //添加和修改
    @RequestMapping("/savecontact")
    public ResultEntity<String> saveContact(@RequestBody Contact contact){
        try {
            Integer integer=0;
            if (contact.getId() == null) {
                //添加
                integer = contactService.add(contact);
            } else {
                //修改
                integer = contactService.update(contact);
            }
            return ResultEntity.successWithoutData(integer+"");
        }catch (Exception ex) {
            return ResultEntity.failed(ex.getMessage());
        }
    }
    //根据id查询
    @RequestMapping("/select/contact/by/id")
    public ResultEntity<Contact> getContactById(Integer id){
        Contact contact=contactService.selectById(id);
        return ResultEntity.successWithoutData(contact);
    }
    //根据id删除
    @RequestMapping("/delContactById")
    public ResultEntity<String> delContactById(Integer id){
        try{
            Integer integer=contactService.delete(id);
            return ResultEntity.successWithoutData(integer+"");
        }catch (Exception ex){
            return ResultEntity.failed(ex.getMessage());
        }

    }
}
